﻿using System;
using System.IO;

namespace CSharpExt.IO
{
    public class ByteStream : Stream
    {
        #region Private Data

        private byte[] _buffer = new byte[0];
        private int _length;
        private int _position;

        #endregion

        #region Properties

        public byte[] Buffer
        {
            get { return _buffer; }
        }

        #endregion

        public override void Flush()
        {
            
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    _position = (int) offset;
                    break;

                case SeekOrigin.Current:
                    _position += (int)offset;
                    break;
                    
                case SeekOrigin.End:
                    _position = (int) (_length - offset);
                    break;

                default:
                    _position = (int) offset;
                    break;
            }

            return _position;
        }

        public override void SetLength(long value)
        {
            _length = (int) value;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            ensureSpace(count);
            System.Buffer.BlockCopy(buffer, offset, _buffer, _length, count);
            _length += count;
        }

        private void ensureSpace(int space)
        {
            if (_buffer.Length - _length >= space)
                return;

            int nlength = newlength(space);

            byte[] obuffer = _buffer;
            _buffer = new byte[nlength];
            System.Buffer.BlockCopy(obuffer, 0, _buffer, 0, _length);
        }

        private int newlength(int space)
        {
            int tspace = _length + space;
            int nlength = 1;
            while (nlength < tspace)
                nlength <<= 1;
            return nlength;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override long Length
        {
            get { return _length; }
        }

        public override long Position
        {
            get { return _position;  }
            set { _position = (int) value; }
        }
    }
}
